from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from BigEvent.myTokenObtainPairSerializer import MyTokenObtainPairSerializer
from my.models import User


class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        user = User.objects.filter(username=username).first()
        if user and user.check_password(password):
            refresh = MyTokenObtainPairSerializer.get_token(user)

            data = {
                'code':0,
                'msg':'登陆成功',
                'user_id':user.id,
                'refresh': str(refresh),
                'access': str(refresh.access_token),
            }
            return data
        else:
            raise ValidationError('用户名或密码错误')


